package com.lzw.controller;

import com.lzw.app.Instance;
import com.lzw.app.ServerApp;
import com.lzw.data.AppRepository;
import com.lzw.property.LzwProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author LZW
 */
@RestController
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private ServerApp serverApp;

    @Autowired
    private LzwProperties lzwProperties;
    //{name:"app",status:"OK",ip:"192.168.145.133",port:"8080",url:"http://192.168.145.133:8080/"}

    /**
     * 获取集群的信息
     */
    @GetMapping("/servers")
    public List getInfoOfServers(){
        AppRepository serverRepository = serverApp.getServerRepository();
        Map<String, Map<String, Instance>> data = serverRepository.getData();
        List result = getList(data);
        return result;
    }

    /**
     * 获取服务的信息
     */
    @GetMapping("/services")
    public List getInfoOfServices(){
        AppRepository appRepository = serverApp.getAppRepository();
        Map<String, Map<String, Instance>> data = appRepository.getData();
        List result = getList(data);
        return result;
    }

    private List getList(Map<String, Map<String, Instance>> data) {
        ArrayList<Map> result = new ArrayList<Map>();
        if(data!=null){
            for (String appName : data.keySet()) {
                Map<String, Instance> instanceMap = data.get(appName);
                if(instanceMap!=null){
                    for (String key : instanceMap.keySet()) {
                        Map<String, Object> app = new HashMap<String, Object>(16);
                        Instance instance = instanceMap.get(key);
                        String name = instance.getName();
                        String host = instance.getHost();
                        int port = instance.getPort();
                        String url = instance.getUrl();
                        app.put("name",name);
                        app.put("ip",host);
                        app.put("port",port);
                        app.put("url",url);
                        long lastPing = instance.getLastPing();
                        long time = System.currentTimeMillis();
                        if((time-lastPing)<lzwProperties.getPingInterval()*1000){
                            //健康
                            app.put("status","OK");
                        }else if((time-lastPing)>lzwProperties.getInvalidateTime()*1000){
                            app.put("status","ERROR");
                        }else {
                            app.put("status","WARNING");
                        }
                        result.add(app);
                    }
                }
            }
        }
        return result;
    }
}
